// components/calendar/calendar.js
const lunarCalendar = require('./lunar-alendar.js').lunarCalendar
console.log(lunarCalendar);
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // 传入的日期，考虑到兼容性问题，最好传斜杠格式的日期字符串，如： 2021/2/12
    defaultDate: {
      type: String,
      observer() {
        this.getAllYearDays();
        // this.getCurrentDaysAndWeekStart();
        // this.renderDate();
        this.triggerEvent('formatter', this.data.daysArray);
      }
    },
    // 点击今天
    today: {
      type: Boolean,
      value: false,
      observer() {
        this.getAllYearDays();
      }
    },
    // 用户数据是否改变
    isDataChange: {
      type: Boolean,
      value: false,
      observer() {
        this.clickItem1();
        this.triggerEvent('formatter', this.data.daysArray);
      }
    },
    // 传入的日历数据
    daysData: {
      type: Array,
      observer(newVal) {
        if (newVal.length > 0) {
          this.setData({ daysArray: newVal });
        }
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    Y: '', // 年
    M: '', // 月
    D: '', // 日
    W: '', // 星期
    firstDayWeek: '', // 当前月第一天星期几
    lastDayWeek: '',  // 当前月最后一天星期几
    daysCount: 0,  // 总天数
    daysArray: [], // 日历中天数数组
    title: '', // 日历标题
    currentDate: '0', // 当前选中的天
    currentId: 0,
    cuDay: '',
    show: false,
    switch1Checked: false,
    startDate: '',
    startTime: '8:00',
    endDate: '',
    endTime: '22:00',
    array: ['永不', '重复一次'],
    index: 0,
    titleIn: ''
  },

  /**
   * 组件的方法列表
   */
  methods: {
    bindchangeTag(e) {
      var date = `${this.data.Y}/${e.detail.current + 1}/1`
      this.getCurrentDays(date)
    },
    titleInput(e) {
      this.setData({
        titleIn: e.detail.value
      });
    },
    addDate() {
      this.setData({
        show: !this.data.show,
      })
    },
    switch1Change(e) {
      console.log(e)
    },
    startDateChange(e) {
      this.setData({
        startDate: e.detail.value
      })
    },
    startTimeChange(e) {
      this.setData({
        startTime: e.detail.value
      })
    },
    endDateChange(e) {
      this.setData({
        endDate: e.detail.value
      })
    },
    endTimeChange(e) {
      this.setData({
        endTime: e.detail.value
      })
    },
    bindPickerChange: function (e) {
      console.log('picker发送选择改变，携带值为', e.detail.value)
      this.setData({
        index: e.detail.value
      })
    },
    //点击添加
    addClick() {
      if(!this.data.titleIn){
        wx.showModal({
          title:'提示',
          content:'请输入标题',
          showCancel:false
        })
        return;
      };
      var date = this.data.startDate.split('-');
      var num = parseInt(date[2]);
      var swiper_data = this.data.swiper_data;
      swiper_data[this.data.M - 1].forEach(ele => {
        if (ele.date == num) {
          ele.content.push({
            title: this.data.titleIn
          });
          ele.topText = '有日程';
        }
      })
      wx.setStorageSync('swiper_data', swiper_data);
      this.setData({
        swiper_data: swiper_data
      })
      wx.showModal({
        title: '提示',
        content: "添加成功,是否关闭弹窗？",
        //成功后传值
        success: (res) => {
          let that = this;
          let userId = wx.getStorageSync('userId')
          console.log(userId);
          console.log(that.data.startDate)
          console.log(that.data.startTime)
          console.log(that.data.startTime)
          console.log(that.data.endTime)
          // wx.request({
          //   url:'http://172.17.60.141/AddEventsServlet', 
          //   data: {
          //     user:userId,
          //   },
          //   header: {
          //     "Content-Type": "application/x-www-form-urlencoded"
          //   },
          //   method: 'POST',
          //   // header: {}, // 设置请求的 header 默认是application/json
          //   success: function (res) {
          //       console.log(res.data)
          //       that.setData({       //this.setData的方法用于把传递过来的id转化成小程序模板语言
          //       data: res.data    //拿到该商品详情对应的商品id，再调用getProdutInfo方法
          //     })
          //   },
          //   fail: function () {
          //     // fail
          //     console.log("false");
          //   },
          //   complete: function () {
          //     // complete
          //   }
          // })
          if (res.confirm) {
            this.setData({
              show: false,
              isDataChange: !this.properties.isDataChange,
              titleIn: ''
            })
          }
        }
      })
    },
    getCurrentDays(date) {
      let today = new Date(date);
      let Y = today.getFullYear();
      let M = today.getMonth() + 1;
      let D = today.getDate();
      let daysCount = new Date(Y, M, 0).getDate(); // 当前月最后一天日期，即当前月的天数
      let firstDayWeek = new Date(Y, M - 1, 1).getDay(); // 第一天星期几
      let lastDayWeek = new Date(Y, M, 0).getDay(); // 最后一天星期几
      this.setData({
        Y: Y,
        M: M,
        D: D,
        firstDayWeek: firstDayWeek,
        lastDayWeek: lastDayWeek,
        daysCount: daysCount,
        currentDate:'32',
        title: `${Y}年${M}月`,
        startDate: `${Y}-${M}-${D}`,
        endDate: `${Y}-${M}-${D}`
      });
    },
    // 获取当前月的天数，以及当前月第一天是星期几，最后一天是星期几
    getCurrentDaysAndWeekStart() {
      let dateString = this.properties.defaultDate;
      let today = new Date();
      if (dateString) {
        today = new Date(dateString);
      }
      let Y = today.getFullYear();
      let M = today.getMonth() + 1;
      let D = today.getDate();
      let daysCount = new Date(Y, M, 0).getDate(); // 当前月最后一天日期，即当前月的天数
      let firstDayWeek = new Date(Y, M - 1, 1).getDay(); // 第一天星期几
      let lastDayWeek = new Date(Y, M, 0).getDay(); // 最后一天星期几
      this.setData({
        Y: Y,
        M: M,
        D: D,
        firstDayWeek: firstDayWeek,
        lastDayWeek: lastDayWeek,
        daysCount: daysCount,
        currentDate: 1,
        title: `${Y}年${M}月`,
        startDate: `${Y}-${M}-${D}`,
        endDate: `${Y}-${M}-${D}`
      });
    },

    // 根据总天数和第一天星期几，最后一天星期几，渲染日历天数数组
    renderDate() {
      let firstDayWeek = this.data.firstDayWeek;
      let lastDayWeek = this.data.lastDayWeek;
      let daysCount = this.data.daysCount;
      let days = []; // 当前月总天数数组
      for (let i = 1; i <= daysCount; i++) {
        days.push({
          date: i.toString(),
          topText: '',
          bottomText: ''
        });
      }

      // 补全前面 (因为一周七天，如果第一天是星期三，则需要把星期一和星期二数据补全)
      for (let i = 0; i < firstDayWeek; i++) {
        days.unshift({
          date: '',
          topText: '',
          bottomText: ''
        });
      }

      // 补全后面 (因为一周七天，如果最后一天是星期五，则需要把星期六和星期天数据补全)
      for (let i = lastDayWeek; i <= 7; i++) {
        days.push({
          date: '',
          topText: '',
          bottomText: ''
        });
      }
      this.setData({ daysArray: days });
    },

    // 点击单个日期事件
    clickItem(event) {
      let date = event.currentTarget.dataset.date;
      if (date) {
        this.setData({
          currentDate: date,
          // D: date,
          startDate: `${this.data.Y}-${this.data.M}-${date}`,
          endDate: `${this.data.Y}-${this.data.M}-${date}`
        });
        var swiper_data = this.data.swiper_data;
        var content = []
        swiper_data[this.data.M - 1].forEach(ele => {
          if (ele.date == date) {
            content = ele.content;
          }
        })
        // this.triggerEvent('select', `${this.data.Y}-${this.data.M}-${date}`);
        this.triggerEvent('select', { Y: this.data.Y, M: this.data.M, D: this.data.currentDate, content: content });
      }
    },
    // 默认弹出
    clickItem1() {
      var swiper_data = wx.getStorageSync('swiper_data');;
      var content = ''
      swiper_data[this.data.M - 1].forEach(ele => {
        if (ele.date == this.data.currentDate) {
          content = ele.content;
        }
      })
      this.setData({
        swiper_data: swiper_data
      })
      // this.triggerEvent('select', `${this.data.Y}-${this.data.M}-${date}`);
      this.triggerEvent('select', { Y: this.data.Y, M: this.data.M, D: this.data.currentDate, content: content });
    },
    //获取全部月份
    //获取全年的日期
    getAllYearDays() {
      var datea = this.properties.defaultDate;
      var dateb = datea.split('/');
      var date = new Date();
      var month = date.getMonth() + 1
      this.setData({
        cuDay:date.getDate()
      })
      if (wx.getStorageSync('swiper_data')) {
        var swiper_data = wx.getStorageSync('swiper_data');
        swiper_data.forEach((ele, inx) => {
          if ((inx + 1) == dateb[1]) {
            let today = new Date();
            today = new Date(datea);
            let Y = today.getFullYear();
            let M = today.getMonth() + 1;
            let D = today.getDate();
            let daysCount = new Date(Y, M, 0).getDate(); // 当前月最后一天日期，即当前月的天数
            let firstDayWeek = new Date(Y, M - 1, 1).getDay(); // 第一天星期几
            let lastDayWeek = new Date(Y, M, 0).getDay(); // 最后一天星期几
            this.setData({
              Y: Y,
              M: M,
              D: D,
              firstDayWeek: firstDayWeek,
              lastDayWeek: lastDayWeek,
              daysCount: daysCount,
              currentDate: dateb[2],
              title: `${Y}年${M}月`,
              currentId: M - 1,
              startDate: `${Y}-${M}-${D}`,
              endDate: `${Y}-${M}-${D}`
            });
          }
        })

        this.setData({
          swiper_data: swiper_data,
        });
        this.clickItem1();
        return;
      }
      var swiper_data = [];
      for (var i = 1; i < 13; i++) {
        let today = new Date();
        today = new Date(`${dateb[0]}/${i}/1`);
        let Y = today.getFullYear();
        let M = today.getMonth() + 1;
        let D = today.getDate();
        let daysCount = new Date(Y, M, 0).getDate(); // 当前月最后一天日期，即当前月的天数
        let firstDayWeek = new Date(Y, M - 1, 1).getDay(); // 第一天星期几
        let lastDayWeek = new Date(Y, M, 0).getDay(); // 最后一天星期几
        if (i == dateb[1]) {
          this.setData({
            Y: Y,
            M: M,
            D: D,
            firstDayWeek: firstDayWeek,
            lastDayWeek: lastDayWeek,
            daysCount: daysCount,
            currentDate: dateb[2],
            title: `${Y}年${M}月`,
            currentId: M - 1,
            startDate: `${Y}-${M}-${D}`,
            endDate: `${Y}-${M}-${D}`
          });
        }
        let days = []; // 当前月总天数数组
        for (let i = 1; i <= daysCount; i++) {
          const peasant = lunarCalendar.solar2lunar(Y, M, i);
          days.push({
            date: i.toString(),
            topText: '',
            bottomText: peasant.IDayCn,
            content: [],
          });
        }

        // 补全前面 (因为一周七天，如果第一天是星期三，则需要把星期一和星期二数据补全)
        for (let i = 0; i < firstDayWeek; i++) {
          days.unshift({
            date: '',
            topText: '',
            bottomText: '',
            content: [],
          });
        }
        // 补全后面 (因为一周七天，如果最后一天是星期五，则需要把星期六和星期天数据补全)
        for (let i = lastDayWeek; i <= 7; i++) {
          days.push({
            date: '',
            topText: '',
            bottomText: '',
            content: [],
          });
        }
        swiper_data.push(days);
      }
      wx.setStorageSync('swiper_data', swiper_data)
      this.setData({
        swiper_data: swiper_data,
      });
      this.clickItem1();
    },
  }
})
